<!DOCTYPE html>
<html lang="zh">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>
    
    ES6 函数参数的默认值设置 - DSRBLOG
    
  </title>
  

  
  
  <link href="atom.xml" rel="alternate" title="DSRBLOG" type="application/atom+xml">
  <link rel="stylesheet" href="asset/css/style.min.css">
  <link rel="stylesheet" href="asset/css/doc.css">
  <script src="asset/app.js"></script>


</head>

<body> <section class="ct-body">
	<div class="container">
		<div class="columns is-variable bd-klmn-columns is-4 is-centered">
			<div class="column is-four-fifths">
				<div class="post-body single-content">
					
					<h1 class="title">
						ES6 函数参数的默认值设置
					</h1>


					<div class="media">
						
						
						<div class="media-content">
							<div class="content">
								<p>
									<span class="date">2022/08/16 01:04 上午</span>
									

									

									<br />
									<span class="tran-tags">Tags:</span>&nbsp;
									
									<a class="tag is-link is-light">#ES6新特性</a>
									

								</p>
							</div>
						</div>

					</div>
				</div>
				<article class="markdown-body single-content">
					<p><code>ES6</code>允许给函数参数（形参）赋初始值</p>
<h2><a id="%E5%BD%A2%E5%8F%82%E5%88%9D%E5%A7%8B%E5%80%BC" class="anchor" aria-hidden="true"><span class="octicon octicon-link"></span></a>形参初始值</h2>
<p>具有默认值的参数，一般位置要靠后</p>
<pre class="line-numbers"><code class="language-js">//未赋初始值
function add(a,b,c){
    return a + b + c;
}
let result = add(1,2);
        
console.log(result); //输出‘NaN’，c为undefine
        
//赋初始值
function add(a,b,c=10){
    return a + b + c;
}
let result = add(1,2);
        
console.log(result); //输出‘13’
</code></pre>
<h2><a id="%E4%B8%8E%E8%A7%A3%E6%9E%84%E8%B5%8B%E5%80%BC%E7%BB%93%E5%90%88" class="anchor" aria-hidden="true"><span class="octicon octicon-link"></span></a>与解构赋值结合</h2>
<pre class="line-numbers"><code class="language-js">//一般形式
function connect(options){};

connect({
    host: 'localhost',
    username: 'root',
    password: 'root',
    port: 3306
})

//解构赋值
function connect({host=&quot;127.0.0.1&quot;, username, password, port}){};

connect({
    host: 'localhost', //若未传递host值，则默认为127.0.0.1
    username: 'root',
    password: 'root',
    port: 3306
})
</code></pre>

				</article>
				<div class="comments-wrap">
					<div class="share-comments">
						

						

						
					</div>
				</div><!-- end comments wrap -->
			</div>
		</div><!-- end columns -->
	</div><!-- end container -->
</section>  














<script src="asset/prism.js"></script>









</body>

</html>